﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.DirectoryServices;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace UserAuthentication
{
    public partial class ResetPassword : Form
    {
        public ResetPassword()
        {
            InitializeComponent();
        }

        private void buttonClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public void setUserAccount(string strUserAccount)
        {
            textBoxUserAccount.Text = strUserAccount;
        }

        private void ResetPassword_Load(object sender, EventArgs e)
        {
            textBoxOldPassword.Focus();
        }

        private bool ChangePassword(string userName, string oldPassword, string newPassword)
        {
            //string path = "LDAP://CN=" + userName + ",CN=Users,DC=demo,DC=domain,DC=com";

            //Instantiate a new DirectoryEntry using an administrator uid/pwd
            //In real life, you'd store the admin uid/pwd  elsewhere
            //DirectoryEntry de = new DirectoryEntry(path, "administrator", "password");
            DirectoryEntry de = new DirectoryEntry(null, userName, oldPassword, AuthenticationTypes.Secure);

            try
            {
                de.Invoke("ChangePassword", new object[] { oldPassword, newPassword });
            }
            catch (Exception ex)  //TODO: catch a specific exception ! :)
            {
                MessageBox.Show(string.Format("ex.Message={0}", ex.Message));
                return false;
            }

            return true;
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            string strPassword = textBoxPassword.Text;
            string strPassword2 = textBoxPassword2.Text;

            if (strPassword != strPassword2)
            {
                MessageBox.Show(@"Passwords not identical");
                return;
            }

            if (ChangePassword(textBoxUserAccount.Text, textBoxOldPassword.Text, strPassword))
            {
                MessageBox.Show("Password changed.");
            }
            else
            {
                MessageBox.Show("Password change failed.");
            }
        }
    }
}
